<template>
  <div class="info-area-container" @click.self="handleClickCloseSetting">
    <!-- 左侧控制区 -->
    <!-- :disabled="infoStore.isStarted" -->
    <div class="left-btns">
      <div class="levelNum" v-show="infoStore.isLevelMode">
        第{{ cardStore.levelNum }}关
        <div class="time">{{ formatTime(cardStore.levelTime) }}</div>
      </div>
      <el-button
        type="primary"
        @click="handleClick"
        :style="{
          color: btnFontColor,
          background: btnColor,
          'border-color': '#a5d8ff',
        }"
        >{{ btnContent }}</el-button
      >
      <el-button
        type="primary"
        @click="handleClickLevelMode"
        :style="{
          color: levelFontColor,
          background: levelColor,
          'border-color': '#ffab8a',
        }"
        >{{ levelModeTxt }}</el-button
      >
    </div>

    <!-- 右侧控制区 -->
    <div class="right-btns" style="padding-top: 2px">
      <!-- 卡片池 -->
      <el-tooltip
        class="item"
        effect="dark"
        content="卡片池"
        placement="top-start"
      >
        <el-button
          type="success"
          icon="el-icon-star-off"
          circle
          size="mini"
          @click="handleCardPool"
          :style="{
            background: '#ffae63',
            border: '1px solid #ffae63',
          }"
        ></el-button>
      </el-tooltip>
      <!-- 声音 -->
      <el-tooltip
        class="item"
        effect="dark"
        :content="infoStore.isVolume ? '点击关闭声音' : '点击开启声音'"
        placement="top-start"
      >
        <el-button
          type="success"
          :icon="
            infoStore.isVolume ? 'el-icon-bell' : 'el-icon-close-notification'
          "
          circle
          size="mini"
          @click="handleClickVolume"
          :style="{
            background: `${infoStore.isVolume ? '#67c23a' : '#a2dab5'}`,
            border: '1px solid #a2dab5',
          }"
        ></el-button>
      </el-tooltip>
      <!-- 设置 -->
      <el-tooltip
        class="item"
        effect="dark"
        content="自定义设置"
        placement="top-start"
      >
        <!-- :disabled="infoStore.isStarted" -->
        <el-button
          type="info"
          icon="el-icon-message el-icon-s-tools"
          circle
          size="mini"
          @click="handleSetting"
          :style="{
            background: '#767676',
          }"
        ></el-button>
      </el-tooltip>
      <!-- 信息 -->
      <el-dropdown trigger="click" @command="handleInfoBtn">
        <div class="el-dropdown-link">
          <el-tooltip
            class="item"
            effect="dark"
            content="信息"
            placement="top-start"
          >
            <el-button
              type="success"
              icon="el-icon-info"
              circle
              size="mini"
              :style="{
                background: '#a0ccff',
                border: '1px solid #a0ccff',
              }"
            ></el-button>
          </el-tooltip>
        </div>
        <el-dropdown-menu slot="dropdown">
          <el-dropdown-item command="description">游戏说明</el-dropdown-item>
          <el-dropdown-item command="cardPool">关于卡片池</el-dropdown-item>
          <el-dropdown-item command="versions">历史版本V1+</el-dropdown-item>
          <el-dropdown-item command="versions2">历史版本V2+</el-dropdown-item>
          <el-dropdown-item command="afterUpdate">预更新内容</el-dropdown-item>
          <el-dropdown-item command="download">下载/更新APP</el-dropdown-item>
          <el-dropdown-item command="about">关于</el-dropdown-item>
        </el-dropdown-menu>
      </el-dropdown>
    </div>
  </div>
</template>
<script>
import delay from "@/utils/delay";
import closeTips from "@/utils/closeTips";
import formatTime from "@/utils/formatTime";
import startVoice from "@/assets/audio/clickVoice/3.mp3";
import levelData from "@/store/levelData";
export default {
  data() {
    return {
      infoStore: this.$store.state.info,
      cardStore: this.$store.state.cards,
      versionStore: this.$store.state.versions,
      btnContent: "开始游戏", // 开始按钮的文本内容
      btnColor: "#409eff", // 开始按钮的颜色
      btnFontColor: "#fff", // 开始按钮的字体颜色
      levelModeTxt: "关卡模式", // 关卡模式的文本内容
      levelColor: "linear-gradient(135deg,#ffab8a,#a44343)", // 按钮颜色
      levelFontColor: "#fff", // 字体颜色
      isShowing: false, // 版本相关信息是否正在展示的过程中
      isShowNext: false, // 版本相关信息能否继续显示
      popOffset: this.$store.state.info.isMobile ? 148 : 60, // 弹窗距顶部的偏移量
    };
  },
  async mounted() {
    // 监听游戏区的卡片成功点击事件
    this.$bus.$on("successClick", this.handleSuccessClick);
    // 监听卡槽区卡片消除的事件
    this.$bus.$on("clearCards", this.handleClearCards);
    // 监听游戏结束事件
    this.$bus.$on("gameOver", this.handleGameOver);
    // 监听游戏胜利事件
    this.$bus.$on("gameWin", this.handleGameWin);
    // await delay(800);
    // // 右侧通知1
    // this.notice(
    //   this.versionStore.versions[this.versionStore.versions.length - 2],
    //   "top-right",
    //   7000
    // );
    await delay(1000);
    // 右侧通知2
    const versions =
      this.versionStore.versions3 ||
      this.versionStore.versions2 ||
      this.versionStore.versions;
    this.notice(
      versions[versions.length - 1],
      "top-right",
      (versions[versions.length - 1].content.length / 4) * 1200 + 1500
    );
  },
  beforeDestroy() {
    // 移除监听
    this.$bus.$off("successClick", this.handleSuccessClick);
    this.$bus.$off("clearCards", this.handleClearCards);
    this.$bus.$off("gameOver", this.handleGameOver);
    this.$bus.$off("gameWin", this.handleGameWin);
  },
  methods: {
    formatTime,
    // 点击后关闭设置窗口和卡片池窗口
    handleClickCloseSetting() {
      // this.$store.commit("info/setIsShowSetting", false);
      this.$bus.$emit("clickSetting", false);
      this.$bus.$emit("clickCardPool", true);
      closeTips();
    },
    // "开始游戏"
    handleClick() {
      if (this.infoStore.isBanCardClick || this.infoStore.isLevelMode) {
        // 如果禁止点击卡片或者正在关卡模式
        return;
      }
      if (this.infoStore.isStarted) {
        // 结束游戏
        this.gameEnd();
        return;
      }
      console.log("游戏开始!");
      // 卡片种类数不变, 种类随机
      this.$store.commit("info/setCardTypes", this.infoStore.cardTypes.length);
      if (this.infoStore.isVolume) {
        var player = new Audio(startVoice);
        player.play(); //播放 mp3这个音频对象
      }
      // 弹窗
      this.$message({
        showClose: true,
        message: "游戏开始!",
        type: "success",
        duration: 3000,
        offset: this.popOffset,
      });
      this.btnContent = "结束本局";
      this.btnColor = "#a0ccff";
      this.btnFontColor = "#1f7fed";
      closeTips(); // 清除所有tip小窗
      this.$bus.$emit("clickCardPool", true); // 关闭卡片池窗口
      this.$bus.$emit("gameStart");
    },
    // "关卡模式"
    handleClickLevelMode() {
      if (this.infoStore.isBanCardClick || this.infoStore.isBanLevelModeBtn) {
        return; // 禁止点击
      }
      if (!this.infoStore.isLevelMode) {
        if (this.infoStore.isStarted) {
          // 游戏[普通模式]已经开始
          return;
        }
        this.btnColor = "#a0ccff";
        this.btnFontColor = "#1f7fed";
        closeTips(); // 清除所有tip小窗
        this.$bus.$emit("clickCardPool", true); // 关闭卡片池窗口
        // 开始关卡模式
        this.$bus.$emit("levelModeStart"); // 抛出"开始关卡模式"事件
        this.$store.commit("info/setIsLevelMode", true);
        this.levelModeTxt = "结束挑战";
        this.levelColor = "linear-gradient(135deg,#ff966c,#882c2c)";
        console.log("开始关卡模式");
        if (this.infoStore.isVolume) {
          var player = new Audio(startVoice);
          player.play(); //播放 mp3这个音频对象
        }
        // 弹窗
        this.$message({
          showClose: true,
          message: `挑战开始！第 ${this.cardStore.levelNum} 关`,
          type: "success",
          duration: 3000,
          offset: this.popOffset,
        });
      } else {
        // 结束关卡模式
        this.levelModeTxt = "关卡模式";
        this.levelColor = "linear-gradient(135deg,#ffab8a,#a44343)";
        clearInterval(this.cardStore.levelTimerId); // 暂停计时
        this.$store.commit("cards/setLevelTime", 0); // 计时归0
        this.gameEnd();
      }
    },
    // 点击卡片池的处理函数
    handleCardPool() {
      this.$bus.$emit("clickCardPool");
    },
    // 点击设置的处理函数
    handleSetting() {
      if (this.infoStore.isStarted) {
        this.$message({
          showClose: true,
          message: "游戏过程中不可进行自定义设置呢",
          type: "error",
          duration: 3000,
          offset: this.popOffset,
        });
        return;
      }
      // 抛出点击设置的事件
      this.$bus.$emit("clickSetting");
    },
    // 游戏版本的信息是否应该[继续]展示
    async retIsShowing() {
      const isStarted = this.infoStore.isStarted;
      if (isStarted && this.infoStore.isMobile) {
        // 手机端在游戏开始后会中断显示版本信息
        if (this.isShowing) {
          // 中断正在展示的进度
          this.$message({
            showClose: true,
            message: "请在结束游戏后再继续查看相关信息吧",
            type: "warning",
            duration: 3500,
            offset: this.popOffset,
          });
        } else {
          // 禁止展示
          this.$message({
            showClose: true,
            message: "请在结束游戏后再查看相关信息吧",
            type: "error",
            duration: 3500,
            offset: this.popOffset,
          });
        }
        return false;
      }
      if (!this.isStarted && !this.isShowing) {
        this.$message({
          showClose: true,
          message: "正在显示版本相关信息, 再次点击可终止继续显示",
          type: "warning",
          duration: 3500,
          offset: this.popOffset,
        });
        this.isShowing = true;
      }
      return true;
    },
    // 点击信息按钮的处理函数
    async handleInfoBtn(itemName) {
      // console.log(itemName);
      if (this.isShowNext) {
        this.$message({
          showClose: true,
          message: "已终止版本相关信息继续显示",
          type: "success",
          duration: 3000,
          offset: this.popOffset,
        });
        this.isShowNext = false;
      } else {
        if (
          itemName === "afterUpdate" ||
          itemName === "versions" ||
          itemName === "versions2" ||
          itemName === "versions3"
        ) {
          if (!this.isShowing) {
            this.isShowNext = true; // 结束显示后才能继续显示下一个
          }
        }
      }
      if (itemName === "download") {
        // 下载/更新App
        let url = "https://pan.baidu.com/s/1qU1NnYikmX1nDNJ7K5nkTg?pwd=hmyj";
        if (this.infoStore.isMobile) {
          // 移动端
          plus.runtime.openURL(url, function (e) {
            plus.nativeUI.toast("安装更新失败！" + e.message);
          });
        } else {
          // PC端
          window.open(url);
        }
      }
      // 如果正在显示
      if (this.isShowing) {
        return;
      }
      if (
        itemName === "versions" ||
        itemName === "versions2" ||
        itemName === "versions3"
      ) {
        const versions = itemName; // 当前点击的按钮的版本
        // console.log(versions);
        // 显示历史版本 [V1+ 或 V2+]
        for (let i = 0; i < this.versionStore[versions].length; i++) {
          // 判断放在循环里面是因为可能信息还在展示中 [循环还未结束]
          const isNext = await this.retIsShowing();
          if (!isNext || !this.isShowNext) {
            this.isShowing = false;
            this.isShowNext = false;
            return;
          }
          const duration =
            (this.versionStore[versions][i].content.length / 4) * 800 + 1500;
          this.notice(this.versionStore[versions][i], "top-right", duration);
          await delay(duration - 1000);
        }
      } else if (itemName === "afterUpdate") {
        // 显示预更新版本
        for (let i = 0; i < this.versionStore.afterUpdate.length; i++) {
          const isNext = await this.retIsShowing();
          if (!isNext || !this.isShowNext) {
            this.isShowing = false;
            this.isShowNext = false;
            return;
          }
          const duration =
            this.versionStore.afterUpdate[i].content.length * 200 + 1400;
          this.notice(this.versionStore.afterUpdate[i], "top-right", duration);
          await delay(duration - 1000);
        }
      } else if (itemName === "description") {
        // 游戏说明
        const duration =
          (this.versionStore.description.content.length / 8) * 2500 + 1500;
        this.notice(this.versionStore.description, "top-right", duration);
      } else if (itemName === "cardPool") {
        // 关于卡片池
        const duration =
          (this.versionStore.cardPool.content.length / 8) * 2500 + 1500;
        this.notice(this.versionStore.cardPool, "top-right", duration);
      } else if (itemName === "about") {
        // 关于
        const duration = (this.versionStore.about.content.length / 8) * 2600;
        this.notice(this.versionStore.about, "top-right", duration);
      }
      this.isShowing = false;
      this.isShowNext = false;
    },
    // 成功点击
    handleSuccessClick(data) {
      if (!this.infoStore.isVolume || !data.voice) {
        return;
      }
      data.volume = data.volume || 1; // 默认音量大小为100%
      var player = new Audio(data.voice);
      player.volume = data.volume; // 设置音量
      player.play(); //播放 mp3这个音频对象
      //暂停
      //player.pause();
      //player.load();
    },
    // 卡片消除
    handleClearCards(data) {
      if (!this.infoStore.isVolume) {
        return;
      }
      data.volume = data.volume || 1; // 默认音量大小为100%
      var player = new Audio(data.voice);
      player.volume = data.volume; // 设置音量
      player.play(); //播放 mp3这个音频对象
    },
    // 失败
    async handleGameOver() {
      if (this.infoStore.isLevelMode) {
        // 关卡
        const msg = `第 ${this.cardStore.levelNum} 关挑战失败`;
        console.log(msg);
        // 弹窗
        this.$message({
          showClose: true,
          message: msg,
          duration: 4000,
          type: "error",
          offset: this.popOffset,
        });
        clearInterval(this.cardStore.levelTimerId); // 暂停计时器
        this.$store.commit("info/setIsBanCardClick", true);
        await delay(1000);
        this.$store.commit("info/setIsBanCardClick", false);
        this.$store.commit("cards/setLevelTime", 0); // 重置时间
      } else {
        // 普通
        console.log("Game Over ! ! !");
        // 弹窗
        this.$message({
          showClose: true,
          message: "Game Over ! ! !",
          duration: 4000,
          type: "error",
          offset: this.popOffset,
        });
        this.$store.commit("info/setIsBanCardClick", true);
        await delay(1000);
        this.$store.commit("info/setIsBanCardClick", false);
      }
      this.gameEnd();
    },
    // 胜利
    async handleGameWin() {
      console.log("挑战成功 ! ! !");
      if (this.infoStore.isLevelMode) {
        console.log(this.infoStore.isBanCardClick);
        // 关卡模式挑战成功弹窗
        this.$message({
          showClose: true,
          message: `第${this.cardStore.levelNum}关挑战成功! ${
            levelData[this.cardStore.levelNum].msg
          }`,
          duration: 5000,
          type: "success",
          offset: this.popOffset,
        });
        if (this.cardStore.levelNum >= levelData.length) {
          this.$store.commit("cards/setLevelNum", 1); // 重置关卡数
          await delay(10);
          this.gameEnd();
          this.$store.commit("cards/putLevel"); // 保存仓库的关卡进度至本地
        }
        this.$store.commit("cards/resetUseNum"); // 重置卡片使用次数
        this.$store.commit("info/gameReset"); // 清空游戏区和卡槽
        this.$bus.$emit("levelModeSuccess");
        return;
      } else {
        // 普通模式挑战成功弹窗
        this.$message({
          showClose: true,
          message: "恭喜你挑战成功 ! ! !",
          duration: 5000,
          type: "success",
          offset: this.popOffset,
        });
      }
      this.gameEnd();
    },
    // 声音
    handleClickVolume() {
      this.$store.commit("info/setIsVolume", !this.infoStore.isVolume);
    },
    // 通知 [默认显示在右上角]
    notice(msg, position = "top-right", duration = 4000) {
      // msg > { title: xxx, msg: xxx }
      const h = this.$createElement;
      this.$notify({
        title: msg.title,
        message: h("i", { style: "color: teal" }, msg.content),
        position,
        duration,
      });
    },
    // 游戏结束时候的部分通用代码
    gameEnd() {
      this.btnContent = "开始游戏";
      this.levelModeTxt = "关卡模式";
      this.btnColor = "#409eff";
      this.btnFontColor = "#fff";
      this.$store.commit("info/setIsStarted", false);
      this.$store.commit("info/setIsLevelMode", false);
      this.$store.commit("cards/resetUseNum"); // 重置卡片使用次数
      this.$store.commit("info/gameReset");
    },
  },
};
</script>

<style lang="less" scoped>
@H: 45px;
.info-area-container {
  display: flex;
  justify-content: space-between;
  position: relative;
  width: 430px;
  height: @H;
  margin: 0 auto;
  button.el-button--primary {
    border-radius: 8px;
  }
  .left-btns {
    height: @H;
    // 当前关卡
    .levelNum {
      display: flex;
      position: absolute;
      top: -30px;
      left: 5px;
      letter-spacing: 2px;
      font-size: 16px;
      font-weight: bold;
      color: #566e84;
      .time {
        margin-left: 20px;
      }
    }
    display: flex;
  }
  .right-btns {
    display: flex;
    height: @H;
    button.el-button.is-circle {
      font-size: 20px;
      margin-left: 10px;
      width: 38px;
      height: 38px;
    }
  }
  .el-button.el-button--primary {
    font-size: 16px;
  }
}
// 版本
ul.el-dropdown-menu.el-popper {
  text-align: center;
  li.el-dropdown-menu__item {
    height: 30px;
    line-height: 30px;
    font-size: 14px;
  }
}
</style>
